package com.cheche.dn.domain.admin;

import com.cheche.dn.Result;
import com.cheche.dn.common.base.Service;
import com.cheche.dn.infrastructure.security.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * Created by cheshun on 15/9/2.
 */
@org.springframework.stereotype.Service
public class AdminService {

    @Autowired
    private Service service;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private TokenService tokenService;

    public Result resetPassword(Admin admin, String password) {
        admin.setPassword(passwordEncoder.encode(password));
        service.update(admin);
        tokenService.clearAdminToken(admin.getId());
        return Result.success();
    }

    /**
     * 删除不可用权限
     * @param availableAuthorities 可用权限
     */
    @Transactional
    public void deleteAuthority(Set<Authority> availableAuthorities) {
        List<Authority> allAuthorities = service.findAll(Authority.class);
        for (Authority authority : allAuthorities) {
            if (!availableAuthorities.contains(authority)) {
                Set<Role> roles = authority.getRoles();
                for (Role role : roles) {
                    Set<Authority> authoritySet = role.getAuthorities();
                    authoritySet.remove(authority);
                    service.update(role);
                }
                service.delete(authority);
            }
        }
    }
}
